package org.jeecg.config;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CustomUserDetailsService implements UserDetailsService {
    private final ISysBaseAPI sysBaseAPI;

    public CustomUserDetailsService(ISysBaseAPI sysBaseAPI) {
        this.sysBaseAPI = sysBaseAPI;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final List<String> roles = sysBaseAPI.getRolesByUsername(username);
        final LoginUser sysUser = sysBaseAPI.getUserByName(username);

        final List<SimpleGrantedAuthority> authorityList = Optional.ofNullable(roles).orElse(new ArrayList<>())
                .stream()
                .map(role -> new SimpleGrantedAuthority(role))
                .collect(Collectors.toList());

        return new User(sysUser.getUsername(), sysUser.getPassword(), authorityList);
    }
}